import { ROLE_EMPTY_ERROR } from '@/components/Chat/constants'
import AccreditDia from '@/components/accreditDia/AccreditDia'
import NoPermissionTem from '@/components/antd-comp/NoPermission'
import { showWarning } from '@/components/antd-comp/message/useNotification'
import '@/components/antd-comp/modal/index.less'
import ThemeBtn from '@/components/antd-comp/theme-btn'
import DialogForceUpdate from '@/components/bs-ui/dialog/DialogForceUpdate'
import FouterPage from '@/components/fouter-page'
import { Func } from '@/permissions/constants'
import { useDictStore } from '@/store/dictStore'
import { useFuncsStore } from '@/store/funcStore'
import { useRouteStoreHook } from '@/store/routeStore'
import { useBuriedEvent } from '@/util/buried'
import { ExclamationCircleFilled } from '@ant-design/icons'
import { Button, Modal } from 'antd'
import { useEffect, useState, useContext } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router-dom'
import CardComponent from '../../components/bs-comp/cardComponent'
import { AssistantItemDB, deleteAssistantApi, getAssistantsApi } from '../../controllers/API/assistant'
import { FlowType } from '../../types/flow'
import { useTable } from '../../util/hook'
import { topLineOffline } from '../ApplicationTopLine/API'
import ApplicHeader from './components/ApplicHeader'
import CreateApplication from './components/CreateApplication'
import { userContext } from '../../contexts/userContext'
const { confirm } = Modal

export default function Assistants() {
  const { t } = useTranslation()
  // ------埋点------
  const { applicationBuriedEvent } = useBuriedEvent()
  const { user } = useContext(userContext)
  /**
   * 涉及顶部路由信息，在对应页面进行处理
   */
  const routeNames = [t('menu.application')]
  useRouteStoreHook(routeNames)

  /**
   * 功能权限限制
   */
  const { hasFuncPermission } = useFuncsStore()
  const navigate = useNavigate()
  const [open, setOpen] = useState(false)
  const {
    page,
    pageSize,
    data: dataSource,
    total,
    loading,
    setPage,
    search,
    reload,
    refreshData
  } = useTable<AssistantItemDB>(
    { pageSize: 15 },
    param => getAssistantsApi(param.page, param.pageSize, searchName, num || null, status === 2 ? null : status),
    true,
    () => hasFuncPermission([Func.assistant.query])
  )
  const handleDelete = data => {
    applicationBuriedEvent({
      event_name: '【删除】智能体按钮',
      data_id: data.id
    })

    if (!hasFuncPermission([Func.assistant.del])) {
      return
    }
    confirm({
      title: t('prompt'),
      icon: <ExclamationCircleFilled style={{ color: 'red' }} />,
      content: t('deleteAssistant'),
      okText: t('delete'),
      okType: 'danger',
      cancelText: t('cancel'),
      autoFocusButton: null,
      centered: true,
      destroyOnClose: true,
      onOk() {
        deleteAssistantApi(data.id)
          .then(() => {
            applicationBuriedEvent({
              event_name: '确定【删除】智能体按钮',
              data_id: data.id,
              detail: JSON.stringify({ 删除结果: '成功' })
            })
            reload()
          })
          .catch(() => {
            applicationBuriedEvent({
              event_name: '确定【删除】智能体按钮',
              data_id: data.id,
              detail: JSON.stringify({ 删除结果: '失败' })
            })
          })
      }
    })
  }
  /* switch = false modal弹窗提醒 */
  const handleCheckedChange = async (checked, data) => {
    if (checked) {
      if (!data.prompt) {
        showWarning('提示', ROLE_EMPTY_ERROR)
      } else {
        navigate('/applicationEdit/topLine/' + data.id)
      }
      return false
    }
    if (!checked) {
      applicationBuriedEvent({
        event_name: '【下线】按钮',
        data_id: data.id
      })
    }
    if (!checked) {
      return new Promise(resolve => {
        const modal = confirm({
          icon: null,
          title: t('build.warn'),
          closable: true,
          content: (
            <div className="flexRowStart">
              <span style={{ fontSize: '14px', fontWeight: '400', color: '#131921', margin: '12px 0 30px' }}>
                {t('build.warnCont')}
              </span>
            </div>
          ),
          centered: true,
          style: { width: '400px' },
          footer: (
            <div className="flexRow">
              <Button
                key="cancel"
                onClick={e => {
                  applicationBuriedEvent({
                    event_name: '取消【下线】按钮',
                    data_id: data.id
                  })
                  resolve(false)
                  modal.destroy()
                }}
                style={{ marginRight: '6px' }}
                className="closeBtnStyles closeBtnWid application_leftBtn"
                shape="round"
              >
                {t('cancel')}
              </Button>
              <ThemeBtn
                onClick={e => {
                  // modalSwitch(checked, data)
                  topLineOffline(data.id).then(res => {
                    console.log(res, '====')
                    modal.destroy()
                    resolve(true)
                  })
                }}
                key="create"
                style={{ marginLeft: '6px' }}
                className="closeBtnWid application_rightBtn"
              >
                {t('confirmButton')}
              </ThemeBtn>
            </div>
          )
        })
      })
    }
    // return await modalSwitch(checked, data)
  }

  // const modalSwitch = (checked, data) => {
  //   return captureAndAlertRequestErrorHoc(changeAssistantStatusApi(data.id, checked ? 1 : 0)).then(res => {
  //     if (res === null) {
  //       applicationBuriedEvent({
  //         event_name: checked ? '【上线】按钮' : '【确定】下线按钮',
  //         data_id: data.id,
  //         detail: JSON.stringify({ 结果: '成功' })
  //       })
  //       showMessage({
  //         content: checked ? '上线成功' : '下线成功',
  //         type: 'success'
  //       })
  //       refreshData(item => item.id === data.id, { status: checked ? 1 : 0 })
  //     } else {
  //       applicationBuriedEvent({
  //         event_name: checked ? '【上线】按钮' : '【确定】下线按钮',
  //         data_id: data.id,
  //         detail: JSON.stringify({ 结果: '失败' })
  //       })
  //     }
  //     return res
  //   })
  // }
  // 类型列表
  const [SearchList, setSearchList] = useState([])
  const [SearchListDialog, setSearchListDialog] = useState([])
  const { loadDictOptions } = useDictStore()
  const loadTypeList = (type = 'category') => {
    loadDictOptions(type).then((res: any) => {
      const list = [...res]
      setSearchListDialog(list)
      res.unshift({
        id: 0,
        label: '全部类型',
        value: 'all'
      })
      setSearchList(res)
      setNum(res[0].id)
    })
  }
  /* input */
  const [searchName, setsearchName] = useState('')
  const [num, setNum] = useState('')
  /* 筛选状态 */
  const [status, setStatus] = useState(2)

  const seleCarFun = (e, id) => {
    setNum(e.id)
    search(e.id)
    applicationBuriedEvent({
      event_name: '搜索条件',
      detail: JSON.stringify({ 搜索条件: searchName, 类型: e.id })
    })
  }
  /* 初始化类别列表 */
  useEffect(() => {
    if(user.user_name === 'admin') {
      loadTypeList()
    }else{
      setSearchList([])
      setSearchListDialog([])
    }
  
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-expect-error
    const _page = window.LibPage
    if (_page) {
      setPage(_page)
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      delete window.LibPage
    } else {
      setPage(1)
    }
  }, [])
  /* 权限 */
  const [accredit, setAccredit] = useState(false)

  if (!hasFuncPermission([Func.assistant.menu], false)) {
    return <NoPermissionTem />
  }

  return (
    <div className="relative h-full" style={{ background: '#F5F7FB' }}>
      <ApplicHeader
        SearchList={SearchList}
        num={num}
        seleCarFun={seleCarFun}
        searchFun={(e, type) => {
          if (type === 'searchName') {
            setsearchName(e.target.value)
            applicationBuriedEvent({
              event_name: '搜索条件',
              detail: JSON.stringify({ 搜索条件: e.target.value, 类型: num })
            })
          } else if (type === 'searchType') {
            setStatus(e)
          }
          search(e)
        }}
      ></ApplicHeader>
      <div className="pageBackColor_callPage_applicationPage relative top-[0] max-h-[calc(100vh-170px)] overflow-y-scroll pl-[40px] pr-[24px] scrollbar-hide">
        {/* list */}
        {loading && (
          <div className="absolute left-0 top-0 z-10 flex h-full w-full items-center justify-center bg-[rgba(245,247,251,1)] dark:bg-blur-shared">
            <span className="loading loading-infinity loading-lg"></span>
          </div>
        )}

        <div className="caseMarginBot flex flex-wrap gap-[16px]">
          {/* 创建助手 */}
          <DialogForceUpdate
            trigger={
              <CardComponent<FlowType>
                data={null}
                type="skill"
                title={t('application.titleName')}
                description={
                  <>
                    <span>{t('application.titleContent')}</span>
                    {/* <span>{t('build.nextDescription')}</span> */}
                    <div className="flexRow">
                      <Button
                        style={{
                          border: '1px solid #5964F3',
                          color: '#5964F3',
                          background: '#F5F7FB',
                          marginTop: '12px',
                          fontWeight: '600',
                          fontSize: '14px'
                        }}
                      >
                        {t('application.appliPageDiaTitle')}
                      </Button>
                    </div>
                  </>
                }
                onClick={() => {
                  applicationBuriedEvent({
                    event_name: '【创建智能体】按钮'
                  })
                  if (!hasFuncPermission([Func.assistant.add])) {
                    return
                  }
                  setOpen(true)
                }}
              ></CardComponent>
            }
          >
            <></>
          </DialogForceUpdate>
          {dataSource.map((item: any, i) => (
            <CardComponent<AssistantItemDB>
              data={item}
              id={item.id}
              key={item.id}
              edit={true}
              logo={item.logo ? item.logo : ''}
              checked={item.status === 1}
              type="assist"
              title={item.name}
              description={item.desc}
              user={item.user_name}
              // item.status !== 1
              onClick={() => {
                if (!hasFuncPermission([Func.assistant.detail])) {
                  return
                }
                navigate('/applicationEdit/' + item.id)
              }}
              onDelete={handleDelete}
              onSetting={() => {
                applicationBuriedEvent({
                  event_name: '【编辑】智能体按钮',
                  data_id: item.id
                })
                if (!hasFuncPermission([Func.assistant.edit])) {
                  return
                }
                navigate('/applicationEdit/' + item.id)
              }}
              onCheckedChange={handleCheckedChange}
              onAccreditDia={() => {
                setAccredit(true)
              }}
            ></CardComponent>
          ))}
        </div>
      </div>
      {/* footer */}
      <FouterPage page={page} pageSize={pageSize} total={total} setPage={setPage}></FouterPage>
      {open ? (
        <CreateApplication
          open={open}
          setOpen={setOpen}
          dataSource={dataSource || []}
          obj={{}}
          dropList={SearchListDialog}
          onSave={{}}
        ></CreateApplication>
      ) : null}
      {/* 分配权限 */}
      {accredit && (
        <AccreditDia
          cancel={() => {
            setAccredit(false)
          }}
          submit={() => {
            setAccredit(false)
          }}
        />
      )}
    </div>
  )
}
